package 小样例.生成二维码;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

public class QRCodeGenerator {

    public static void main(String[] args) {
        String content = "https://baidu.com";
        int width = 300;
        int height = 300;
        String fileType = "png";
        Path filePath = Paths.get("a.png"); // You can specify the path where you want to save the QR code image

        generateQRCode(content, width, height, fileType, filePath);
    }

    public static void generateQRCode(String content, int width, int height, String fileType, Path filePath) {

        // 创建一个Map对象，用于存放编码的提示信息
        Map<EncodeHintType, Object> hints = new HashMap<>();
        // 设置编码的纠错等级
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        // 设置编码的字符集
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");


        // 创建一个QRCodeWriter对象
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        try {
            // 使用QRCodeWriter的encode方法，根据content、BarcodeFormat、width、height、hints参数，生成一个BitMatrix对象
            BitMatrix bitMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints);


            // 获取BitMatrix的宽度
            int matrixWidth = bitMatrix.getWidth();
            // 创建一个BufferedImage对象，用于存放编码后的图片
            BufferedImage image = new BufferedImage(matrixWidth, matrixWidth, BufferedImage.TYPE_INT_RGB);
            image.createGraphics();

            // 获取Graphics2D对象，用于绘制图片
            Graphics2D graphics = (Graphics2D) image.getGraphics();
            // 设置图片的背景颜色
            graphics.setColor(Color.WHITE);
            graphics.fillRect(0, 0, matrixWidth, matrixWidth);
            // 设置图片的 foreground color
            graphics.setColor(Color.BLACK);


            // 遍历BitMatrix，根据bitMatrix的值，判断是否需要绘制矩形
            for (int i = 0; i < matrixWidth; i++) {
                for (int j = 0; j < matrixWidth; j++) {
                    if (bitMatrix.get(i, j)) {
                        graphics.fillRect(i, j, 1, 1);
                    }
                }
            }


            // 如果filePath不为空，则将图片保存到指定路径
            if (filePath != null) {
                File outputFile = filePath.toFile();
                ImageIO.write(image, fileType, outputFile);
            }

        } catch (WriterException | IOException e) {
            e.printStackTrace();
        }
    }

}
